#
# Hill, Seth J. and Chris Tausanovitch. "A Disconnect in Representation? Comparison of Trends in Congressional and Public Polarization."
#

library(rjags)

load("senateOutBig10k.RData")

normalizeMultinomial <- function(output,n,m){
  bmin <- min(grep("beta",colnames(output)))
  bmax <- max(grep("beta",colnames(output)))
  amin <- min(grep("alpha",colnames(output)))
  amax <- max(grep("alpha",colnames(output)))
  xmin <- min(grep("x",colnames(output)))
  xmax <- max(grep("x",colnames(output)))

  x <- output[,xmin:xmax]
  alpha <- output[,amin:amax]
  beta <- output[,bmin:bmax]
  
  the999s <- which(alpha==999)

  for (i in 1:dim(output)[1]){
    print(i)
    sdx <- sd(x[i,])
    meanx <- mean(x[i,])
    x[i,] <- (x[i,] - meanx)/sdx
    alpha[i,] <- alpha[i,] - beta[i,]*meanx
    beta[i,] <- beta[i,]*sdx
  }
  alpha[the999s] <- NA
  beta[the999s] <- NA
  return(list(x=x,beta=beta,alpha=alpha))
}

output <- normalizeMultinomial(output[[1]],merged$n,merged$m)

save("output","merged",file="senateBig10k.RData")

